<?php

defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' );

/**
 *  Functions to syncronize orderstatus from Gambio to Shopgate
 * 
 *  Include this File in Gambio /admin/orders.php
 *  
 *  @author Martin Weber
 *  @version 1.0.0
 *  @revision $rev$
 */

include_once dirname(__FILE__).'/../../includes.php';

function getOrderShopgateNumber($orderId) {
	if(empty($orderId)) return;
	
	$qry = xtc_db_input("SELECT shopgate_order_number FROM `".TABLE_SHOPGATE_ORDERS."` WHERE orders_id = $orderId LIMIT 1");
	
	$qry = xtc_db_query($qry);
	$sgOrder = xtc_db_fetch_array($qry);
	
	if(!empty($sgOrder))
		$sgOrder = $sgOrder["shopgate_order_number"];
		
	return $sgOrder;
}

function getOrderShopgateNumbers($orderIds) {
	$orderNumbers = array();
	
	$qry = xtc_db_input("SELECT orders_id, shopgate_order_number FROM ".TABLE_SHOPGATE_ORDERS." WHERE orders_id IN (" . implode(", ", $orderIds) . ")");
	$qry = xtc_db_query($qry);
	
	while($sgOrder = xtc_db_fetch_array($qry)) {
			$orderNumbers[$sgOrder["orders_id"]] = $sgOrder["shopgate_order_number"];
	}
	
	return $orderNumbers;
}

function setShopgateOrderStatus($oID, $status) {
	try {
		$shopgate_config = ShopgateConfig::validateAndReturnConfig();
		$sendStatus = 3;
		
		if(isset($shopgate_config["order_shipped_status"]))
			$sendStatus = $shopgate_config["order_shipped_status"];
			
		if($status == $sendStatus) {
			$sgOrderNumber = getOrderShopgateNumber($oID);
			if(empty($sgOrderNumber)) return;
			
			$order = new ShopgateOrder();
			$order->setOrderNumber($sgOrderNumber);
			
			try {
				$orderApi = new ShopgateOrderApi();
				$orderApi->setShippingComplete($order);
				
				$statusArr = array(
					"orders_id" => $oID,
					"orders_status_id" => $status,
					"date_added" => date( 'Y-m-d H:i:s' ),
					"customer_notified" => 1,
					"comments" => "Bestellung wurde bei Shopgate als versendet markiert",
				);
				
				xtc_db_perform(TABLE_ORDERS_STATUS_HISTORY, $statusArr);
			} catch (ShopgateFrameworkException $e) {
				$response = utf8_decode($e->lastResponse["error_text"]);
				
				$statusArr = array(
					"orders_id" => $oID,
					"orders_status_id" => $status,
					"date_added" => date( 'Y-m-d H:i:s' ),
					"customer_notified" => 0,
					"comments" => 'Ein fehler ist aufgetreten: ' . $response,
				);
				
				xtc_db_perform(TABLE_ORDERS_STATUS_HISTORY, $statusArr);
			}
		}
	} catch (Exception $e) {
		ShopgateFrameworkCore::logWrite(print_r($e,true));
	}
}

function setShopgateOrderlistStatus($oIDs, $status) {
	$ordersHistories = array();
	
	try {
		$shopgate_config = ShopgateConfig::validateAndReturnConfig();
		$sendStatus = 3;
		
		if(isset($shopgate_config["order_shipped_status"]))
			$sendStatus = $shopgate_config["order_shipped_status"];
			
		if($status == $sendStatus) {
			$sgOrders = array();
			$sgOrderNumbers = getOrderShopgateNumbers($oIDs);
			if(empty($sgOrderNumbers)) return;
			
			foreach ($sgOrderNumbers as $oID => $sgOrderNumber) {
				$_sgOrder = new ShopgateOrder();
				$_sgOrder->setOrderNumber($sgOrderNumber);
				$sgOrders[] = $_sgOrder;
				
				$ordersHistories[$sgOrderNumber] = array(
					"orders_id" => $oID,
					"orders_status_id" => $status,
					"date_added" => "now()",
					"customer_notified" => 1,
					"comments" => "Bestellung wurde bei Shopgate als versendet markiert",
				);
			}

			try {
				$orderApi = new ShopgateOrderApi();
				$orderApi->setShippingCompletelist($sgOrders);
				
			} catch (ShopgateFrameworkException $e) {
				$response = utf8_decode($e->lastResponse["error_text"]);
				
				$errors = json_decode($e->lastResponse["error_details"], true);
				foreach ($errors as $orderNumber => $error) {
					if(isset($ordersHistories[$orderNumber])) {
						$ordersHistories[$orderNumber]["comments"] = utf8_decode('Ein fehler ist aufgetreten: ' . $error["message"]);
						$ordersHistories[$orderNumber]["customer_notified"] = 0;
					}
				}
			}
			
			foreach($ordersHistories as $ordersHistory) {
				xtc_db_perform(TABLE_ORDERS_STATUS_HISTORY, $ordersHistory);
			}
		}
	} catch (Exception $e) {
		ShopgateFrameworkCore::logWrite(print_r($e,true));
	}
}
